#!/usr/bin/env python
# -*- coding: utf8 -*-
# 文件xml格式保存
import sys
from xml.etree import ElementTree
from xml.etree.ElementTree import Element, SubElement
from lxml import etree
import codecs

from numpy import unicode

XML_EXT = '.xml'
ENCODE_METHOD = 'utf-8'


class PascalVocWriter:

    def __init__(self, foldername, filename, imgSize, databaseSrc='Unknown', localImgPath=None):
        self.foldername = foldername
        self.filename = filename
        self.databaseSrc = databaseSrc
        self.imgSize = imgSize
        self.boxlist = []
        self.polygonlist = []
        self.localImgPath = localImgPath
        self.verified = False
        # print("XML保存数据", self.foldername, self.filename, self.imgSize)

    def prettify(self, elem):
        """
            Return a pretty-printed XML string for the Element.
        """
        rough_string = ElementTree.tostring(elem, 'utf8')
        root = etree.fromstring(rough_string)
        return etree.tostring(root, pretty_print=True, encoding=ENCODE_METHOD).replace("  ".encode(), "\t".encode())
        # minidom does not support UTF-8
        '''reparsed = minidom.parseString(rough_string)
        return reparsed.toprettyxml(indent="\t", encoding=ENCODE_METHOD)'''

    def genXML(self):
        """
            Return XML root
        """
        # Check conditions
        if self.filename is None or \
                self.foldername is None or \
                self.imgSize is None:
            return None

        top = Element('annotation')
        if self.verified:
            top.set()

        folder = SubElement(top, 'folder')
        folder.text = self.foldername

        filename = SubElement(top, 'filename')
        filename.text = self.filename

        if self.localImgPath is not None:
            localImgPath = SubElement(top, 'path')
            localImgPath.text = self.localImgPath

        source = SubElement(top, 'source')
        database = SubElement(source, 'database')
        database.text = self.databaseSrc

        size_part = SubElement(top, 'size')
        width = SubElement(size_part, 'width')
        height = SubElement(size_part, 'height')
        depth = SubElement(size_part, 'depth')
        width.text = str(self.imgSize[1])
        height.text = str(self.imgSize[0])
        if len(self.imgSize) == 3:
            depth.text = str(self.imgSize[2])
        else:
            depth.text = '1'

        segmented = SubElement(top, 'segmented')
        segmented.text = '0'
        return top

    def addBndBox(self, xmin, ymin, xmax, ymax, name, difficult):
        bndbox = {'xmin': xmin, 'ymin': ymin, 'xmax': xmax, 'ymax': ymax}
        bndbox['name'] = name
        bndbox['difficult'] = difficult
        self.boxlist.append(bndbox)

    def addpolygonBox(self, x, name, difficult):
        polygonBox = {'x': x}
        polygonBox['name'] = name
        polygonBox['difficult'] = difficult
        self.polygonlist.append(polygonBox)
        # print("self.polygonlist", self.polygonlist)

    def appendObjects(self, top):
        for each_object in self.boxlist:
            object_item = SubElement(top, 'object')
            name = SubElement(object_item, 'name')
            try:
                name.text = unicode(each_object['name'])
            except NameError:
                # Py3: NameError: name 'unicode' is not defined
                name.text = each_object['name']
            pose = SubElement(object_item, 'pose')
            pose.text = "Unspecified"
            truncated = SubElement(object_item, 'truncated')
            truncated.text = "0"
            difficult = SubElement(object_item, 'difficult')
            difficult.text = "0"
            # if int(each_object['ymax']) == int(self.imgSize[0]) or (int(each_object['ymin']) == 1):
            #     truncated.text = "1"  # max == height or min
            # elif (int(each_object['xmax']) == (self.imgSize[1])) or (int(each_object['xmin']) == 1):
            #     truncated.text = "1"  # max == width or min
            # else:
            #     truncated.text = "0"
            # difficult = SubElement(object_item, 'difficult')
            # difficult.text = str(bool(each_object['difficult']) & 1)
            bndbox = SubElement(object_item, 'bndbox')
            xmin = SubElement(bndbox, 'xmin')
            xmin.text = str(each_object['xmin'])
            ymin = SubElement(bndbox, 'ymin')
            ymin.text = str(each_object['ymin'])
            xmax = SubElement(bndbox, 'xmax')
            xmax.text = str(each_object['xmax'])
            ymax = SubElement(bndbox, 'ymax')
            ymax.text = str(each_object['ymax'])

            # bndbox = SubElement(object_item, 'bndbox')
            # xmin = SubElement(bndbox, 'xmin')
            # xmin.text = str(each_object['xmin'])
            # ymin = SubElement(bndbox, 'ymin')

        for each_polygon in self.polygonlist:
            object_item = SubElement(top, 'object')
            name = SubElement(object_item, 'name')
            try:
                name.text = unicode(each_polygon['name'])
            except NameError:
                # Py3: NameError: name 'unicode' is not defined
                name.text = each_polygon['name']
            pose = SubElement(object_item, 'pose')
            pose.text = "Unspecified"
            truncated = SubElement(object_item, 'truncated')
            truncated.text = "0"
            difficult = SubElement(object_item, 'difficult')
            difficult.text = "0"
            polygon = SubElement(object_item, 'polygon')
            for index, i in enumerate(each_polygon['x']):
                munber_x = int(i[0])
                munber_y = int(i[1])
                # print("x,y", munber_x, munber_y, index+1)
                index1 = index + 1
                name_x = "x" + str(index1)
                name_y = "y" + str(index1)
                # print("name_x", name_x, name_y)
                x = SubElement(polygon, name_x)
                x.text = str(munber_x)
                y = SubElement(polygon, name_y)
                y.text = str(munber_y)

    def save(self, targetFile=None):
        root = self.genXML()
        self.appendObjects(root)
        out_file = None
        if targetFile is None:
            out_file = codecs.open(
                self.filename + XML_EXT, 'w', encoding=ENCODE_METHOD)
        else:
            out_file = codecs.open(targetFile, 'w', encoding=ENCODE_METHOD)

        prettifyResult = self.prettify(root)
        out_file.write(prettifyResult.decode('utf8'))
        out_file.close()


class PascalVocReader:

    def __init__(self, filepath):
        # shapes type:
        # [labbel, [(x1,y1), (x2,y2), (x3,y3), (x4,y4)], color, color, difficult]
        self.shapes = []
        self.filepath = filepath
        self.verified = False
        try:  # 用来尝试一下，跑的通就运行，跑不通就except
            self.parseXML()
        except:
            print("显示-错误")

    def getShapes(self):
        return self.shapes

    def addShape(self, label, difficult, bndbox=None, polygon=None):
        points_polygon1 = []
        points_polygon_list = []
        if bndbox is not None:
            xmin = int(bndbox.find('xmin').text)
            ymin = int(bndbox.find('ymin').text)
            xmax = int(bndbox.find('xmax').text)
            ymax = int(bndbox.find('ymax').text)
            points_bndbox = [(xmin, ymin), (xmax, ymin), (xmax, ymax), (xmin, ymax)]
            self.shapes.append((label, points_bndbox, None, None, difficult))
        else:
            for xy in polygon:
                number1 = xy.text
                points_polygon1.append(number1)
            points_polygon_x = points_polygon1[0::2]
            points_polygon_y = points_polygon1[1::2]
            for i in range(len(points_polygon_x)):
                polygon_x = points_polygon_x[i - 1]
                polygon_y = points_polygon_y[i - 1]
                points_polygon = (int(polygon_x), int(polygon_y))
                points_polygon_list.append(points_polygon)
            self.shapes.append((label, points_polygon_list, None, None, difficult))

    def parseXML(self):
        """解析xml文件"""
        assert self.filepath.endswith(XML_EXT), "Unsupport file format"
        parser = etree.XMLParser(encoding=ENCODE_METHOD)
        xmltree = ElementTree.parse(self.filepath, parser=parser).getroot()
        for object_iter in xmltree:  # 问题在于为空
            if object_iter.tag == "object":
                for list1 in object_iter:
                    label = object_iter.find('name').text
                    if list1.tag == "bndbox":
                        bndbox = object_iter.find("bndbox")
                        difficult = False
                        self.addShape(label, difficult, bndbox)
                    elif list1.tag == "polygon":
                        polygon = object_iter.find("polygon")
                        difficult = False
                        bndbox = None
                        self.addShape(label, difficult, bndbox, polygon)
        return True
